import axios from 'axios'

export default {
    // 开启命名空间
    namespaced: true,
    // 返回一个对象
    state: () => ({
        cart: []
    }),
    mutations: {
        updatedCaet(state, cart) {
            state.cart = cart
        },
        updatedCaetState(state, payload) {
            let index = state.cart.findIndex((item) =>
                item.id == payload.id
            )
            state.cart[index].goods_state = payload.value
        },
        updatedCaetCount(state, payload) {
            let index = state.cart.findIndex((item) =>
                item.id == payload.id
            )
            state.cart[index].goods_count = payload.value
        },
        updateAllState(state, val) {
            state.cart.forEach(item => item.goods_state = val)
        }
    },
    // 
    actions: {
        async getCsrList(context) {
            const res = await axios.get('https://www.escook.cn/api/cart')
            console.log(res.data.list);
            context.commit('updatedCaet', res.data.list)
        }
    },
    getters: {
        // 设置全局的计算属性
        allPrice(state) {
            return state.cart.filter(item => item.goods_state)
                .reduce((sum, item) => sum += item.goods_count * item.goods_price, 0)
        },
        allCound(state) {
            return state.cart.filter(item => item.goods_state)
                .reduce((sum, item) => sum += item.goods_count, 0)
        }
    }
}